// 1.引入模板
const Koa = require('koa'),
  koaBody = require('koa-body'),
  router = require('koa-router')(),
  render = require('koa-art-template'),
  static = require('koa-static'),
  path = require('path'),
  session = require('koa-session'),
  home = require('./routers/home'),
  fs = require('fs'),
  helper = require('../utils/helper');

// 2.实例化Koa对象
const app = new Koa();


// 添加root根路径
let root = __dirname;

// 3.使用中间件
// 3.1 配置静态资源目录
app.use(static('static'));
// 3.2 配置路由的渲染模板  模板文件默认放在view下
render(app, {
    root: path.join(__dirname, 'view'),
    extname: ".html",
    debug:process.env.NODE_ENV !== 'production'
});
// 3.3 配置koa-body接受前端的请求体数据
app.use(koaBody({
    multipart: true,
}));

// 3.4 配置session    cookie中的key值不适用中间件
app.keys = ['some secret hurr'];
const CONFIG = {
    key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
    /** (number || 'session') maxAge in ms (default is 1 days) */
    /** 'session' will result in a cookie that expires when session/browser is closed */
      /** Warning: If a session cookie is stolen, this cookie will never expire */
      // 默认有效期1天
    maxAge: 86400000,
  
    autoCommit: true, /** (boolean) automatically commit headers (default true) */
  //     能不能写
    overwrite: true, /** (boolean) can overwrite or not (default true) */
  //   cookie是否只有服务端可以访问
    httpOnly: true, /** (boolean) httpOnly or not (default true) */
  //   签名
    signed: true, /** (boolean) signed or not (default true) */
  //   
    rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  //是否可以覆盖，到期前进行访问，更新到期时间
    renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  //   使用https进行访问 ，需要改成http改成false
    secure: false, /** (boolean) secure cookie*/
    sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
  };
  
  app.use(session(CONFIG, app));
  // or if you prefer all default config, just use => app.use(session(app));
  


// 配置404
app.use(async (ctx, next) => {
    await next();
    if (ctx.status === 404) {
        ctx.body =ctx.status+ '页面不存在';
    }
    
})




// 4.配置路由
// 使用routers 下的路由作为首页 引入模块路由  
// home.js下面使用的路由都是以router.use('/xxx')为起始，定义的/home就代表/xxx/home
router.use('/home',home)


// 添加路由登录界面
router.get('/login', ctx => {
  ctx.render('login')
})


// 接受登录请求的参数loginsubmit  登录名admin 密码admin
router.post('/loginsubmit', ctx => {
  //接受的是键值对 结构赋值
  let {username,pwd} = ctx.request.body;
  // 1.判断登录名密码的正确性
  if (username && pwd) {
    if (username == 'admin' && pwd == "admin") {
      ctx.cookies.set('username', username, {
        domain: '127.0.0.1',
        // path: '/',
        maxAge: 60 * 60 * 24,
        expires: new Date('2021-09-01'),
        httpOnly: false,
        overwrite:false,
        
      });
      ctx.redirect('/home');
    } else {
      ctx.body='登录失败，用户名或密码错误'
    }
  } else {
    ctx.body="请输入用户名和密码"
  }
})

// 添加注册的路由
router.get('/register', ctx => {
  ctx.render('register');
})

// 接受注册的表单数据
router.post("/register/add", ctx => {
  let res = ctx.request.body;
  console.log(res);
  let poster = ctx.request.files.poster;
  // 上传封面
  if (poster) {
    let posterFileName = helper.upload(poster);
  };
  // 返回成功给前端
  ctx.body = 'success'

})


// 上传图片
//编辑器图片上传
router.post("/register/upload", ctx =>{

  //目标文件
  let dst = root + '/static/uploads' 

  //接收附件
  let img = ctx.request.files.file
  
  //新建文件名
  let date = new Date()
  let dt = date.getTime()
  
  //随机数
  let rand = parseInt(Math.random()*1000)

  //新文件名
  let newTitle = dt +''+ rand

  //扩展名
  let nameArr = img.name.split(".")
  let extension = nameArr[nameArr.length-1]

  //最终的文件路径
  let lastFile = dst + '/' + newTitle + '.' + extension //d:/web04327/node/static/uploads/x.dsss.xxx.jpg

  //上传到服务器
  //创建可读流
  let readStream = fs.createReadStream(img.path)

  //创建写入流
  let writeStream = fs.createWriteStream(lastFile)

  //管道
  readStream.pipe(writeStream)

  //返回结果给前端layedit
  ctx.body = {
      "code": 0 //0表示成功，其它失败
      ,"msg": "上传失败" //提示信息 //一般上传失败后返回
      ,"data": {
        "src": "http://localhost:5000/uploads/" + newTitle + '.' + extension
        ,"title": "图片名称" //可选
      }
    }

})




app.use(router.routes())
  .use(router.allowedMethods());
    


// 5.开启服务器监听

app.listen(5000, () => {
    console.log('服务器运行在http://127.0.0.1:5000');
})